package com.acme;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.client.Client;
import com.acme.bankapp.exceptions.BankException;
import com.acme.bankapp.service.bank.BankDataLoaderService;
import com.acme.bankapp.service.bank.BankService;

/**
 * Class handles commands from the client.
 *
 * @author S.Zhidkov
 */
public class CommandHandler {
    public static final String CLOSE_CONNECTION = "bye";
    private static final String ADD_COMMAND = "add>";

    private Bank bank;

    /**
     * Constructor take Bank instance to handle commands associated with this bank.
     *
     * @param bank
     */
    public CommandHandler(Bank bank) {
        this.bank = bank;
    }

    /**
     * Method parse and process commands that come to the server.
     *
     * @param command
     * @throws BankException
     */
    public void processCommand(String command) throws BankException {

        // server side handle this message
        if (CLOSE_CONNECTION.equals(command)) {
            return;
        }

        if (command.startsWith(ADD_COMMAND)) {
            BankDataLoaderService bankDataLoaderService = new BankDataLoaderService();
            String feedString = command.substring(ADD_COMMAND.length());
            Client client = bankDataLoaderService.parseClientFromFeedString(feedString);
            BankService bankService = new BankService();
            bankService.addClient(bank, client);
        }
    }

}
